package com.edvinli.controller;

import com.edvinli.entity.AliOSSProperties;
import com.edvinli.entity.Result;
import com.edvinli.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliOSSProperties aliOSSProperties;
    /**
     * 文件上传，阿里云oss存储
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {

        //获取原始文件名，截取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}",originalFilename);
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //调用阿里云oss，文件上传到oss
        String url = AliyunOSSUtils.upload(aliOSSProperties.getEndpoint(), aliOSSProperties.getBucketName(), file.getBytes(), extName);

        //最终返回文件路径
        return Result.success(url);
    }

    //文件上传，本地存储
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
//        log.info("参数：{},{},{}",username,age,file);
//
//        //获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//
//        //通过uuid生成随机字符串，避免同名文件被覆盖.通过.来截取文件的后缀，最后完成拼接
//        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        //将前端上传的文件，存到本地
//        file.transferTo(new File("C:/mydocument/myCoding/"+newFileName));
//
//        return Result.success(newFileName);
//    }
}
